<template>
<div id="main">
  <div class="nav-contain long">
        <my-nav style="height:0.2rem;" left="首页" mid="返回我的问卷" right="登出" @toHome='toHome' @toAbout='toPersonQuestion' @topChange='topChange'></my-nav>
  </div>
  <div style="width:100%;height:100%;margin-top:3rem;">
  <div v-loading="is_loading">
    <div class="top">
      <div style="height: 8px"></div>
      <el-button
        type="primary"
        icon="el-icon-edit"
        size="medium"
        plain
        @click="toAllAnswers"
      >
        查看所有答卷
      </el-button>
      <el-button
        type="primary"
        icon="el-icon-download"
        size="medium"
        plain
        @click="downloadPDF(headline+'-数据报告')"
      >
        下载报告
      </el-button>
      <div style="height: 8px"></div>
      <hr />
    </div>

    <div style="height: 110px"></div>

    <div
      v-show="message==='none'"
      style="width: 60%; text-align: center; margin: 0 auto"
    >
      您的问卷还没有答卷！
    </div>
    
    <div class="headline" v-show="message==='notNone'">
        <span>{{ headline }}</span>
    </div>

    <div
      class="problem"
      v-for="(problem,index) in questionnaire"
      :key="index"
      v-show="message==='notNone'"
    >

      <div style="height: 40px"></div>

      <p class="problemIndex">第{{ index+1 }}题：</p>
      <p>{{ problem.title }}</p>
      <p style="color: red" v-show="!problem.noneable">*</p>
      <p class="problemType">【{{ problem.type }}】</p>

      <div>

        <el-table
          :data="problem.statistic"
          style="width: 100%"
          :default-sort="{prop: 'date', order: 'descending'}"
          v-show="problem.type!=='填空题' && problem.tableVisible"
          :id="problem.id+'a'"
        >
          <el-table-column
            label="选项"
            sortable
            width="450"
          >
            <div slot-scope="scope">
              <p>{{ scope.row.option }}</p>
              <p v-if="scope.row.right" style="color: #E6A23C">(答案)</p>
            </div>
          </el-table-column>
          <el-table-column
            prop="numPerOption"
            label="小计"
            sortable
            width="100"></el-table-column>
          <el-table-column
            label="比例"
            width="340"
          >
            <el-progress
              slot-scope="scope"
              :text-inside="true"
              :stroke-width="25"
              :percentage="scope.row.numPerOption/problem.total*100"
            ></el-progress>
          </el-table-column>
        </el-table>

        <el-table
          :data="problem.statistic"
          style="width: 100%"
          :default-sort="{prop: 'date', order: 'descending'}"
          v-show="problem.type==='填空题' && problem.tableVisible"
          :id="problem.id+'b'"
        >
          <el-table-column
            prop="index"
            label="序号"
            sortable
            width="300"
          ></el-table-column>
          <el-table-column
            prop="answer"
            label="答案文本"
            sortable
            width="590"
          ></el-table-column>
        </el-table>

        <div style="height: 10px"></div>

        <div
          style="height: 50px"
          v-show="problem.tableVisible"
        >
          <div>本题有效填写人次：{{ problem.total }}</div>
          <div
            v-show="problem.type==='填空题'&&problem.rightAnswer!=='none'"
            style="color: #E6A23C"  
          >
            正确答案：{{ problem.rightAnswer }}
          </div>
        </div>

        <el-button
          type="primary"
          size="mini"
          plain
          @click="showTable(problem)"
          v-text="problem.showInfo"
        ></el-button>
        <el-button
          type="primary"
          size="mini"
          plain
          @click="problem.pieVisible=!problem.pieVisible"
          icon="el-icon-pie-chart"
          v-show="problem.type!=='填空题'"
        >
          饼图  
        </el-button>
        <el-button
          type="primary"
          size="mini"
          plain
          @click="downloadExcel1(problem.id+'a')"
          v-if="problem.type!=='填空题'"
        >
          导出Excel  
        </el-button>
        <el-button
          type="primary"
          size="mini"
          plain
          @click="downloadExcel2(problem.id+'b')"
          v-if="problem.type==='填空题'"
        >
          导出Excel  
        </el-button>

      </div>
      
      <div 
        :id="problem.id"
        style="width: 600px; height:400px; margin: 0 auto"
        v-show="problem.type!=='填空题' && problem.pieVisible"
      ></div>

      
    </div>
    <div style="height: 40px"></div>

    <div 
      id="graph"
      style="width: 800px; height:600px; margin: 0 auto"
      v-show="relation"
    ></div>
  </div>
  </div>
</div>
</template>

<script>

import html2canvas from 'html2canvas';
import JsPDF from 'jspdf'

import * as echarts from 'echarts'

import FileSaver from 'file-saver'
import XLSX from 'xlsx'
import MyNav from '../components/MyNav.vue';

export default {

  name: 'Statistics',
  components: {MyNav},

  data() {
      return {

        message: "none",

        is_loading: true,

        id: "",

        headline: "",
        questionnaire: [],

        relation: false,


        graphData: [{
              name: '节点1'
            }, {
              name: '节点2'
            }, {
              name: '节点3'
            }, {
              name: '节点4'
            }],


        graphLink: [{
              source: '节点1',
              target: '节点2',
              label: {
                normal: {
                  show: true,
                  formatter:'连接1'
                }
              },
            }, {
              source: '节点1',
              target: '节点3'
            }, {
              source: '节点1',
              target: '节点4'
            }],






      };
  },

  mounted() {
    this.is_loading = true
    this.id = this.$route.query.id;
    var that = this;

    this.axios.get("/result/analyze",{qnid: this.id}).then(
      function(response) {
        that.message = response.data.data.message;

        if (that.message === "notNone") {
          that.headline = response.data.data.headline;
          response.data.data.questionnaire.forEach((q) => {
            that.questionnaire.push(q)
          })
          that.questionnaire.forEach(question => {
            question.tableVisible = true;
            question.showInfo = "关闭详细信息";
            question.pieVisible = false;
            if (question.type === "RADIO") question.type = "单选题";
            else if(question.type === "CHECKBOX") question.type = "多选题";
            else if(question.type === "INPUT") question.type = "填空题";
            else if(question.type === "RATING") question.type = "评分题";
            if (question.type != "填空题") {
              question.total = question.statistic.map((x)=>x.numPerOption).reduce((a,b) => a+b)
            }
          });
        }
        
      },
      function () {  }
    )
    .finally(() => this.is_loading = false)
    this.drawPie();
    this.deawGraph();
  },

  methods: {
                topChange:function(){
            console.log('topchange');
            const top=document.querySelector('.nav-contain');
            if(top.className.indexOf('short')!==-1){
                top.classList.remove('short');
                top.classList.add('long');
            }else{
                top.classList.remove('long');
                top.classList.add('short');
            }
            },
            toHome:function(){
                this.$router.push('/home');
            },
            toPersonQuestion:function(){
                this.$router.push('/manage');
            },
    toMyQuestionnaire: function() {
      this.$router.push('/manage');
    },

    toAllAnswers: function() {
      this.$router.push({path: '/answers', query: {id: this.id}});
    },

    downloadPDF: function(name) {

      let DomName = document.body
      console.log("正在帮您导出......");
      window.pageYoffset = 0; // 滚动置顶
      document.documentElement.scrollTop = 0;
      document.body.scrollTop = 0;

      var shareContent = DomName; //需要截图的包裹的（原生的）DOM 对象
      console.log(shareContent); //打印看有没有获取到dom
      var width = shareContent.offsetWidth; //获取dom 宽度
      var height = shareContent.offsetHeight; //获取dom 高度
      var canvas = document.createElement("canvas"); //创建一个canvas节点
      var scale = 2; //定义任意放大倍数 支持小数
      canvas.width = width * scale; //定义canvas 宽度 * 缩放，在此我是把canvas放大了2倍
      canvas.height = height * scale; //定义canvas高度 *缩放
      canvas.getContext("2d").scale(scale, scale); //获取context,设置scale
      html2canvas(DomName, {
        //允许跨域图片的加载
        useCORS: true,
        dpi: window.devicePixelRatio , //将分辨率提高到特定的DPI 提高四倍
        //scale: 2, //按比例增加分辨率
      }).then(function(canvas) {
        var context = canvas.getContext("2d");
        // 【重要】关闭抗锯齿
        context.mozImageSmoothingEnabled = false;
        context.webkitImageSmoothingEnabled = false;
        context.msImageSmoothingEnabled = false;
        context.imageSmoothingEnabled = false;
        var imgData = canvas.toDataURL("image/", 1.0); //转化成base64格式,可上网了解此格式
        var img = new Image();
        img.src = imgData;
        img.onload = function() {
          img.width = img.width / 2; //因为在上面放大了2倍，生成image之后要/2
          img.height = img.height / 2;
          img.style.transform = "scale(0.5)";
          var doc;
          if (this.width > this.height)
            //此可以根据打印的大小进行自动调节
              doc = new JsPDF("l", "mm", [
              this.width * 0.555,
              this.height * 0.555
            ]);
          else {
              doc = new JsPDF("p", "mm", [
              this.width * 0.555,
              this.height * 0.555
            ]);
          }
          doc.addImage(imgData, "jpeg", 10, 0, this.width * 0.505, this.height * 0.545);
          doc.save(name + ".pdf");
          console.log("倒数3秒导出啦");
        };
      });

    },

    downloadExcel1: function(id) {
      // 生成Excel工作簿对象
        var wb = XLSX.utils.table_to_book(document.getElementById(id), {raw:true});
        // 获取二进制字符串作为输出
        var wbout = XLSX.write(wb, {
          bookType: 'xlsx',
          book: true,
          type: 'array',
        })
        try {
          FileSaver.saveAs(
          // Blob: 对象表示一个不可变 原始数据的类文件对象,不一定是JS原生格式的数据。
          // File: 基于Blob，继承了blob的功能并将其扩展使其支持用户系统上的文件。  
            new Blob([wbout], { type: 'appliction/octet-stream' }),
            // 设置导出的文件名称可随意
            'result.xlsx'
          )
        } catch (e) {
          if (typeof console != 'undefined') console.log(e, wbout);
        }
        // 返回一个新创建的Blob对象，其内容由参数中给定的数组串联组成。
        return wbout
    },

    downloadExcel2: function(id) {
      // 生成Excel工作簿对象
        var wb = XLSX.utils.table_to_book(document.getElementById(id), {raw:true});
        // 获取二进制字符串作为输出
        var wbout = XLSX.write(wb, {
          bookType: 'xlsx',
          book: true,
          type: 'array',
        })
        try {
          FileSaver.saveAs(
          // Blob: 对象表示一个不可变 原始数据的类文件对象,不一定是JS原生格式的数据。
          // File: 基于Blob，继承了blob的功能并将其扩展使其支持用户系统上的文件。  
            new Blob([wbout], { type: 'appliction/octet-stream' }),
            // 设置导出的文件名称可随意
            'result.xlsx'
          )
        } catch (e) {
          if (typeof console != 'undefined') console.log(e, wbout);
        }
        // 返回一个新创建的Blob对象，其内容由参数中给定的数组串联组成。
        return wbout
    },

    showTable: function(problem) {
      problem.tableVisible = !problem.tableVisible
      problem.showInfo = problem.tableVisible ? "关闭详细信息" : "显示详细信息"
    },

    drawPie: function() {

      this.questionnaire.forEach(question => {

        var myChart = echarts.init(document.getElementById(question.id));

        var res = [];
        question.statistic.forEach(a => {
          if (question.type !== "多选题")
            res.push({value: a.numPerOption, name: a.option});
          else if (question.type === "多选题")
            res.push({value: a.numPerOption / question.total, name: a.option});
        });
        
        var option = {
        
        series: [
        {
          name: '访问来源',
          type: 'pie',
          radius: '50%',
          data: res,
          itemStyle: {
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            },
            normal: { 
              label: { 
                show: true, 
                formatter: '{b} : {c} ({d}%)' 
              }, 
              labelLine :{show:true} 
            }
          }
        }]
      };
      // 使用刚指定的配置项和数据显示图表。
      myChart.setOption(option);

      });

    },

    deawGraph: function() {
      var chartDom = document.getElementById('graph');
      var myChart = echarts.init(chartDom);

      var d = [];
      this.graphData.forEach(gd => {
        d.push(gd);
      });

      var l = [];
      this.graphLink.forEach(gl => {
        l.push(gl);

      });

      var option;

      option = {
        title: {text: '关联问题关系图'},
        tooltip: {},
        animationDurationUpdate: 1500,
        animationEasingUpdate: 'quinticInOut',
        series: [
          {
            type: 'graph',
            focusNodeAdjacency: true, 
            force: {
              repulsion: 3000,
              edgeLength: [100, 50]
            },
            layout: "force",
            symbolSize: 50,
            label: {show: true},
            edgeSymbol: ['circle', 'arrow'],
            edgeSymbolSize: [4, 10],
            edgeLabel: {fontSize: 20},

            data: d,
            links: l,

            lineStyle: {
              opacity: 0.9,
              width: 2,
              curveness: 0
            }
          }]
        };
        option && myChart.setOption(option);
    }


  }
}
</script>

<style>

  p {
    display: inline-block;
    margin: 2px;
  }

  .top {
    display: flex;
    justify-content: space-around;
    align-items: center;
    width: 100%;
    height: 54px;
    top: 0;
    background-color: #fff;
    z-index: 999;
  }

  .problem {
    width: 60%;
    margin: 0 auto;
  }

  .problemIndex {
    font-weight: bold;
    color: rgb(99, 99, 99);
  }

  .problemType {
    font-weight: 100;
    color: rgb(163, 162, 162);
  }

  .headline {
    width: 50%;
    margin: 0 auto;
    text-align: center;
    font: normal bold 35px serif;
  }
  #main{
   display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
.nav-contain{
  height:15vh;width:100vw;display:flex;justify-content:space-around;align-items:center;
  background-image:url('../assets/survey2.jpg') ;
  background-size: cover;
  opacity: 0.8;
}
.short{
  height:5vh;
  transition: all 0.7s ease-in-out;
}
.long{
  height:15vh;
  transition: all 0.7s ease-in-out;
}
</style>
